import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path:'/login',
    component:Login
  },
  {
    path:'/home',
    component:Home
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
// 路由守卫
router.beforeEach((to,from,next)=>{
  // 如果用户直接访问登录页就直接进入登录页
  if(to.path === '/login') return next()
  // 从session里面获取token值
  const token = window.sessionStorage.getItem('token')
  // 如果没有token就强制进入登录页
  if(!token) return next('/login')
  // 反之就进入首页
  next()
})

export default router
